<template>
  <p-drawer
    placement="right"
    :closable="false"
    width="calc(100vw - 200px)"
    :visible="visible"
    :mask-closable="false"
    :destroy-on-close="true"
    @close="onClose"
  >
    <p-spin :spinning="spinning">
      <TaskTitle :title-name="titleName" icon-name="to do" color="blue" />
      <div class="g-drawer-list-container">
        <div class="g-drawer-progress-container">
          <TitleSecondary title="审批流程图" />
          <ProgressStaus />
        </div>
        <ProgressTransverse
          :node-list="detail.nodeList"
          :name-list="detail.nameList"
        />
        <TitleSecondary title="基本信息" />
        <FormBasicInfoList :form="form" :plan-type="planType" />
        <TitleSecondary title="销售责任人" />
        <TableSaleList
          :data-source="detail.planSales"
          :plan-type="planType"
          style="margin-bottom: 20px"
        />
        <TitleSecondary
          v-if="hasEdit"
          :title="`${PLAN_TYPE[planType]}计划明细`"
        />
        <TablePlanDetail
          v-if="hasEdit"
          ref="table-detail"
          :is-record="true"
          :data-source="planDetailList"
          :local-key="`${PLAN_TYPE[planType]}-group-record`"
          template-name="初版"
          :plan-sales="detail.planSales"
          :plan-sales-id="detail.planSalesId"
          :plan-id="planId"
          :hide-keys="['selection', 'planSalesId', 'relationId']"
          :plan-type="planType"
          :time-range="[form.startTime, form.endTime]"
          :parent-id="form.salesOrganization"
          :default-show="[]"
          :default-fixed="[]"
        />
        <TitleSecondary
          title="操作日志"
          :icon="iconStaus"
          @change="handleChangeIcon"
        />
        <ProgressPortrait
          v-show="isShowProgressPortrait"
          :operation-log="operationLogInformation"
        />
        <BottomLine />
      </div>
      <ButtonGroup
        class="g-drawer-footer"
        :options="filterButtons"
        @click="handleButtonClick"
      />
      <DialogTransfer
        :visible.sync="visibleTransfer"
        :plan-id="planId"
        :click-info="clickInfo"
        @change="onClose"
      />
    </p-spin>
  </p-drawer>
</template>

<script>
import FormBasicInfoList from '@/components/task/FormBasicInfoList.vue';
import TableSaleList from '@/components/task/TableSaleList.vue';
import ProgressTransverse from '@/components/task/ProgressTransverse.vue';
import ProgressPortrait from '@/components/task/ProgressPortrait.vue';
import ProgressStaus from '@/components/task/ProgressStaus.vue';

import { getOperationLog, postPlanGroupRecord } from '@/api/plan';
import TablePlanDetail from '@/components/task/TablePlanDetail.vue';
import DialogTransfer from '@/components/dialog/DialogTransfer.vue';

import { isEmpty } from '@/utils/is';
import DrawerMixin from './mixin';

const requireKey = [
  'customerCode',
  'modelName',
  'modelNumber',
  'application',
  'appearance',
  'modelCutRate',
  'price',
  'quantity',
  'factoryCode',
];

export default {
  components: {
    FormBasicInfoList,
    TablePlanDetail,
    TableSaleList,
    ProgressTransverse,
    ProgressPortrait,
    ProgressStaus,
    DialogTransfer,
  },

  mixins: [DrawerMixin],

  data() {
    return {
      operationLogInformation: [], //操作日志请求返回的信息
      iconStaus: 'down', //icon图片up、down的切换
      planDetailList: [],
      visibleTransfer: false,
    };
  },
  computed: {
    isShowProgressPortrait() {
      return this.iconStaus === 'up';
    },
    form() {
      return this.detail.plan || {};
    },
    footerButtons() {
      return [
        {
          key: 'submit',
          type: 'primary',
          label: '提交',
          auth: true,
        },
        {
          key: 'save',
          label: '保存',
          auth: true,
        },
        {
          key: 'transfer',
          label: '转他人处理',
          auth: true,
        },
        {
          key: 'close',
          label: '返回',
        },
      ];
    },
  },
  methods: {
    async handleChangeIcon(icon) {
      this.iconStaus = icon === 'down' ? 'up' : 'down';
      if (this.operationLogInformation.length === 0) {
        let res = await getOperationLog({
          planNumber: this.planId,
        });
        this.operationLogInformation = res.data.data;
      }
    },
    onClose() {
      this.$emit('update:visible', false);
      this.$emit('fresh');
    },
    async submitData(operating) {
      const startPlanDetailList = this.planDetailList.map((item) => {
        console.log('item: ', item);
        const price = Object.keys(item).reduce((pre, cur) => {
          if (cur.startsWith('pricemonth')) {
            const month = cur.split('_')[1];
            month !== 'total' && (pre[month] = item[cur]);
          }
          return pre;
        }, {});
        const quantity = Object.keys(item).reduce((pre, cur) => {
          if (cur.startsWith('quantitymonth')) {
            const month = cur.split('_')[1];
            month !== 'total' && (pre[month] = item[cur]);
          }
          return pre;
        }, {});
        const temp = Object.keys(item).reduce((pre, cur) => {
          if (cur.includes('month_')) {
            pre[cur] = item[cur];
          }
          return pre;
        }, {});

        const salesGroupName = this.detail.planSales.find(
          (el) => el.id === item.planSalesId
        )?.salesGroupName;
        return {
          relationId: item.relationId,
          appearance: item.appearance,
          factoryCode: item.factoryCode,
          materialCode: item.materialCode,
          bpRelationId: item.bpRelationId,
          category: item.category,
          application: item.application,
          customerCode: item.customerCode?.key,
          customerName: item.customerCode?.label,
          innerItem: item.innerItem,
          item: item.item,
          manufactureArea: item.manufactureArea,
          modelCutRate: item.modelCutRate,
          modelCode: item.modelName?.key,
          modelName: item.modelName?.label,
          modelNumber: item.modelNumber?.key,
          modelInfoName: item.modelNumber?.label,
          remark: item.remark,
          planSalesId: item.planSalesId,
          salesGroupName: salesGroupName,
          price: JSON.stringify(price),
          quantity: JSON.stringify(quantity),
          temp: JSON.stringify(temp),
        };
      });
      if (operating === 0) {
        const isValid = this.checkData(startPlanDetailList);
        if (!isValid) return new Promise(() => {});
        return await postPlanGroupRecord({
          planId: this.planId,
          operating,
          startPlanDetailList,
        });
      } else {
        return await postPlanGroupRecord({
          planId: this.planId,
          // planSalesId: this.detail.planSales[0].id,
          // responsibleId: this.detail.planSales[0].responsibleId,
          operating,
          startPlanDetailList,
        });
      }
    },
    checkData(list) {
      if (!list.length) {
        this.$message.error('请先填写表格内容！');
        return false;
      }
      const index = list.findIndex((item) => {
        const price = JSON.parse(item.price);
        const isPrice = Object.keys(price).some((key) => isEmpty(price[key]));

        const quantity = JSON.parse(item.quantity);
        const isQuantity = Object.keys(quantity).some((key) =>
          isEmpty(quantity[key])
        );
        return (
          isPrice || isQuantity || requireKey.some((key) => isEmpty(item[key]))
        );
      });
      if (index > -1) {
        this.$message.error('计划明细表数据未填写完整，请补充！');
        return false;
      }
      return true;
    },
    closeCallback() {
      this.onClose();
    },
    async submitCallback() {
      await this.submitData(0);
      this.$message.success('提交成功！');
      this.closeCallback();
    },
    async saveCallback() {
      await this.submitData(1);
      this.$message.success('保存成功！');
      this.closeCallback();
    },
    transferCallback() {
      this.visibleTransfer = true;
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
  },
};
</script>

